package com.holy.dm.config

import com.alibaba.druid.pool.DruidDataSource
import com.alibaba.druid.support.http.StatViewServlet
import com.alibaba.druid.support.http.WebStatFilter
import org.springframework.beans.factory.annotation.Configurable
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Primary
import org.springframework.context.support.ResourceBundleMessageSource
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.EnableTransactionManagement

import javax.sql.DataSource

/**
 * Created by fengyoutian on 2017/4/14.
 */

@Configurable
@Component
@EnableTransactionManagement
class DruidDataConfig {

    @Bean
    ServletRegistrationBean druidServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean()
        bean.setServlet new StatViewServlet()
        bean.addUrlMappings '/druid/*'
        bean.addInitParameter 'loginUsername', 'holy'
        bean.addInitParameter 'loginPassword', '123456'
        bean.addInitParameter 'resetEnable', 'false' // 禁用HTML页面上的“Reset All”功能
        bean.addInitParameter 'allow', '127.0.0.1' // IP白名单 (没有配置或者为空，则允许所有访问)
        bean.addInitParameter 'deny', '192.168.199.106' // IP黑名单 (存在共同时，deny优先于allow)
        
        bean
    }

    @Bean
    FilterRegistrationBean druidFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean()
        bean.setFilter new WebStatFilter()
        bean.addUrlPatterns '/*'
        bean.addInitParameter 'exclusions', '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
        bean.addInitParameter 'profileEnable', 'true'
        bean.addInitParameter 'principalCookieName', 'USER_COOKIE'
        bean.addInitParameter 'principalSessionName', 'USER_SESSION'

        bean
    }

    @Bean(name = 'dataSource')
    @Primary
    @ConfigurationProperties(prefix = 'druid.datasource')
    DataSource druidDataSource() {
        new DruidDataSource()
    }

    @Bean
    ResourceBundleMessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource()
        messageSource.setBasename 'config.message'
        messageSource.setDefaultEncoding 'UTF-8'
        messageSource
    }

}
